

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

from openai import OpenAI
client = OpenAI()
model = "gpt-4o-audio-preview"

while True:  
    file_path = input("请输入音频文件的URL（输入'exit'退出程序）: ") 
    if file_path is None or file_path == "" :
        continue
    elif file_path.lower() == 'exit':  
        print("程序退出。\n")  
        break
    user_input = input("请输入提示文字（输入'exit'退出程序）: ")  
    if user_input is None or user_input == "" :
        continue
    elif user_input.lower() == 'exit':  
        print("程序退出。\n")  
        break   
    else:
        # 取得文件后缀
        from pathlib import Path
        file_extension = Path(file_path).suffix
        file_extension = file_extension[1:]
        print(f"文件后缀为：{file_extension}")

        # 取得文件数据
        import requests
        url = file_path
        response = requests.get(url)
        response.raise_for_status()
        audio_data = response.content

        # 编码为base64
        import base64
        encoded_string = base64.b64encode(audio_data).decode('utf-8')
        print(f"编码后的字符串：{encoded_string}")

        # 调用大模型API
        completion = client.chat.completions.create(
            model=model,
            modalities=["text", "audio"],
            audio={"voice": "alloy", "format": f"{file_extension}"},
            messages=[
                {
                    "role": "user",
                    "content": [
                        { 
                            "type": "text",
                            "text": f"{user_input}"
                        },
                        {
                            "type": "input_audio",
                            "input_audio": {
                                "data": f"{encoded_string}",
                                "format": f"{file_extension}"
                            }
                        }
                    ]
                },
            ]
        )

        # 打印结果
        print(f"大模型输出：{completion}")
        print(completion.choices[0].message)